package database

import (
	"fmt"

	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func InitDB(mode string, logger *zap.Logger) (*gorm.DB, error) {
	dbType := viper.GetString(mode + ".database.type")
	fmt.Println("使用的数据库类型为", dbType)
	var db *gorm.DB
	var err error

	switch dbType {
	case "postgres":
		pgDSN := "host=" + viper.GetString(mode+".database.postgres.host") +
			" user=" + viper.GetString(mode+".database.postgres.user") +
			" password=" + viper.GetString(mode+".database.postgres.password") +
			" dbname=" + viper.GetString(mode+".database.postgres.dbname") +
			" port=" + viper.GetString(mode+".database.postgres.port") +
			" sslmode=disable"
		db, err = gorm.Open(postgres.Open(pgDSN), &gorm.Config{})
	case "mysql":
		mysqlDSN := viper.GetString(mode+".database.mysql.user") + ":" +
			viper.GetString(mode+".database.mysql.password") + "@tcp(" +
			viper.GetString(mode+".database.mysql.host") + ":" +
			viper.GetString(mode+".database.mysql.port") + ")/" +
			viper.GetString(mode+".database.mysql.dbname") + "?charset=utf8mb4&parseTime=True&loc=Local"
		db, err = gorm.Open(mysql.Open(mysqlDSN), &gorm.Config{})
	case "sqlite":
		sqliteDSN := viper.GetString(mode + ".database.sqlite.dbname")
		db, err = gorm.Open(sqlite.Open(sqliteDSN), &gorm.Config{})
	default:
		logger.Fatal("Unsupported database type", zap.String("type", dbType))
	}

	if err != nil {
		logger.Error("Failed to connect to database", zap.Error(err))
		return nil, err
	}
	logger.Info("Connected to database", zap.String("type", dbType))
	// err = models.RegisterTables(db)
	// if err != nil {
	// 	logger.Error("数据库初始化迁移失败", zap.Error(err))
	// 	return nil, err
	// }
	return db, nil

}
